
import gradio as gr

from common import db
from common import llm
from common import tomodel as tm


class GradioApp:
    model: tm.TomotaModel
    llmclient: llm.DeepSeekClient
    database: db.Database

    def __init__(self, model: tm.TomotaModel) -> None:
        self.model = model
        self.llmclient = llm.DeepSeekClient.get_instance()
        self.database = db.Database.get_instance()

    def build(self):
        # 自定义CSS样式
        custom_css = """
        .gradio-container {
            max-width: 1600px;
            margin: 0 auto;
            font-family: 'Inter', system-ui, sans-serif;
        }
        .custom-title {
            text-align: center;
            color: #165DFF;
            margin-bottom: 2rem;
            font-weight: 700;
            letter-spacing: -0.025em;
        }
        .tab-item {
            border-radius: 0.5rem;
            padding: 1.5rem;
            background-color: #ffffff;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
        }
        .tab-item:hover {
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
        }
        .custom-btn {
            background: linear-gradient(135deg, #165DFF 0%, #4080FF 100%);
            color: white;
            font-weight: 500;
            border: none;
            transition: all 0.3s ease;
        }
        .custom-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(22, 93, 255, 0.3);
        }
        .custom-btn:active {
            transform: translateY(0);
            box-shadow: 0 2px 6px rgba(22, 93, 255, 0.2);
        }
        .result-panel {
            border-radius: 0.5rem;
            border: 1px solid #e5e7eb;
            padding: 1rem;
            background-color: #f9fafb;
        }
        .parameter-panel {
            border-radius: 0.5rem;
            border: 1px solid #e5e7eb;
            padding: 1.25rem;
            background-color: #f9fafb;
        }
        .logo-container {
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 1.5rem;
        }
        .logo-icon {
            width: 48px;
            height: 48px;
            margin-right: 1rem;
        }
        .analysis-section {
            margin-top: 1.5rem;
        }
        .sql-section {
            margin-top: 1.5rem;
        }
        .step-container {
            display: flex;
            justify-content: space-between;
            margin-bottom: 1rem;
        }
        .step-item {
            display: flex;
            align-items: center;
            padding: 0.5rem 1rem;
            border-radius: 9999px;
            background-color: #f3f4f6;
            color: #4b5563;
            font-weight: 500;
        }
        .step-item.active {
            background-color: #dbeafe;
            color: #1e40af;
        }
        .step-number {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 1.5rem;
            height: 1.5rem;
            border-radius: 50%;
            background-color: #1e40af;
            color: white;
            margin-right: 0.5rem;
            font-size: 0.875rem;
        }
        """

        with gr.Blocks(css=custom_css) as demo:
            # 顶部标题区域
            gr.HTML("""
            <div class="logo-container">
                <svg class="logo-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" stroke="#165DFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M16.2426 7.75736C17.2231 8.73786 17.2231 10.2621 16.2426 11.2426L12 15.4853L9.75736 13.2426C8.77686 12.2621 8.77686 10.7379 9.75736 9.75736C10.7379 8.77686 12.2621 8.77686 13.2426 9.75736L12 11L8 7" stroke="#165DFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M16 12C16 14.2091 14.2091 16 12 16C9.79086 16 8 14.2091 8 12C8 9.79086 9.79086 8 12 8C14.2091 8 16 9.79086 16 12Z" stroke="#165DFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                <h1 class="custom-title text-[clamp(1.8rem,3vw,2.5rem)]">智慧农业数据分析平台</h1>
            </div>
            """)
            
            with gr.Tabs():
                # 番茄疾病识别标签页
                with gr.Tab("番茄疾病识别", id="tab-disease"):
                    gr.HTML("""
                    <div class="tab-item">
                        <h2 class="text-xl font-semibold text-gray-800 mb-4">番茄叶片疾病智能识别系统</h2>
                        <p class="text-gray-600 mb-6">上传番茄叶片图片，系统将自动识别可能存在的疾病并提供分析结果</p>
                        
                        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                            <div class="space-y-6">
                                <div class="result-panel">
                                    <h3 class="font-medium text-gray-700 mb-3">输入区域</h3>
                                    <div class="space-y-4">
                    """)
                    
                    with gr.Row():
                        with gr.Column():
                            img_input = gr.Image(type='pil', label='上传番茄叶片图片', 
                                                elem_classes="border-2 border-dashed border-gray-300 rounded-lg p-2")
                            
                            with gr.Accordion("高级参数设置", open=False):
                                with gr.Column(elem_classes="parameter-panel"):
                                    conf_threshold = gr.Slider(0, 1, 0.25, step=0.05, 
                                                            label="置信度阈值", 
                                                            info="模型预测的最低置信度要求")
                                    iou_threshold = gr.Slider(0, 1, 0.45, step=0.05, 
                                                            label="交并比阈值", 
                                                            info="目标检测中的边界框重叠度阈值")
                            
                            analyze_btn = gr.Button("开始分析", variant="primary", elem_classes="custom-btn")
                    
                    gr.HTML("""
                                    </div>
                                </div>
                            </div>
                            
                            <div class="space-y-6">
                                <div class="result-panel">
                                    <h3 class="font-medium text-gray-700 mb-3">识别结果</h3>
                    """)
                    
                    with gr.Row():
                        with gr.Column():
                            img_output = gr.Image(type='pil', label="识别可视化结果", 
                                                elem_classes="border border-gray-200 rounded-lg")
                            text_output = gr.Textbox(label="疾病识别详细报告", 
                                                    lines=5, 
                                                    elem_classes="border border-gray-200 rounded-lg")
                    
                    gr.HTML("""
                                </div>
                            </div>
                        </div>
                    </div>
                    """)
                    
                    # 设置按钮点击事件
                    analyze_btn.click(
                        fn=self.model.predict,
                        inputs=[img_input, conf_threshold, iou_threshold],
                        outputs=[img_output, text_output]
                    )
                
                # SQL数据分析标签页
                with gr.Tab("SQL数据分析", id="tab-sql"):
                    gr.HTML("""
                    <div class="tab-item">
                        <h2 class="text-xl font-semibold text-gray-800 mb-4">农业数据智能分析系统</h2>
                        <p class="text-gray-600 mb-6">输入你的数据分析需求，系统将自动生成SQL查询语句并展示分析结果</p>
                        
                        <div class="step-container">
                            <div class="step-item active">
                                <span class="step-number">1</span>生成SQL
                            </div>
                            <div class="step-item">
                                <span class="step-number">2</span>执行查询
                            </div>
                            <div class="step-item">
                                <span class="step-number">3</span>生成报告
                            </div>
                        </div>
                        
                        <div class="space-y-6 analysis-section">
                            <div class="result-panel">
                                <h3 class="font-medium text-gray-700 mb-3">分析需求</h3>
                    """)
                    
                    with gr.Row():
                        with gr.Column():
                            user_requirement_input = gr.Textbox(
                                label="请描述你的数据分析需求",
                                placeholder="例如：请生成一个在“12:00:00“至“23:59:59“识别记录时间段之间出现次数最多的病虫害名称的前三名的SQL语句，去除“未达到置信度阈值”的记录，表名为detection。",
                                lines=3,
                                elem_classes="border border-gray-200 rounded-lg"
                            )
                    
                    gr.HTML("""
                            </div>
                            
                            <div class="result-panel">
                                <h3 class="font-medium text-gray-700 mb-3">生成的SQL语句</h3>
                    """)
                    
                    with gr.Row():
                        with gr.Column():
                            sql_output = gr.Textbox(
                                label="",
                                lines=5,
                                interactive=False,
                                elem_classes="border border-gray-200 rounded-lg bg-white"
                            )
                    
                    gr.HTML("""
                            </div>
                            
                            <div class="flex justify-center">
                    """)
                    
                    generate_button = gr.Button("生成SQL语句", variant="primary", elem_classes="custom-btn")
                    
                    gr.HTML("""
                            </div>
                        </div>
                        
                        <div class="space-y-6 sql-section" style="display: none;">
                            <div class="result-panel">
                                <h3 class="font-medium text-gray-700 mb-3">查询结果</h3>
                    """)
                    
                    with gr.Row():
                        with gr.Column():
                            sql_result_output = gr.Textbox(
                                label="",
                                lines=5,
                                interactive=False,
                                elem_classes="border border-gray-200 rounded-lg bg-white"
                            )
                    
                    gr.HTML("""
                            </div>
                            
                            <div class="flex justify-center">
                    """)
                    
                    query_button = gr.Button("执行查询", variant="primary", elem_classes="custom-btn")
                    
                    gr.HTML("""
                            </div>
                        </div>
                        
                        <div class="space-y-6 report-section" style="display: none;">
                            <div class="result-panel">
                                <h3 class="font-medium text-gray-700 mb-3">数据分析报告</h3>
                    """)
                    
                    with gr.Row():
                        with gr.Column():
                            conclusion_output = gr.Textbox(
                                label="",
                                lines=8,
                                interactive=False,
                                elem_classes="border border-gray-200 rounded-lg bg-white"
                            )
                    
                    gr.HTML("""
                            </div>
                            
                            <div class="flex justify-center">
                    """)
                    
                    another_button = gr.Button("生成数据分析报告", variant="primary", elem_classes="custom-btn")
                    
                    gr.HTML("""
                            </div>
                        </div>
                    </div>
                    
                    <script>
                        // 监听生成SQL按钮点击事件，显示SQL结果区域
                        document.querySelector('button[data-testid="component-15"]').addEventListener('click', function() {
                            document.querySelector('.sql-section').style.display = 'block';
                            document.querySelector('.step-container .step-item:nth-child(2)').classList.add('active');
                        });
                        
                        // 监听执行查询按钮点击事件，显示报告区域
                        document.querySelector('button[data-testid="component-20"]').addEventListener('click', function() {
                            document.querySelector('.report-section').style.display = 'block';
                            document.querySelector('.step-container .step-item:nth-child(3)').classList.add('active');
                        });
                    </script>
                    """)
                    
                    # 设置按钮点击事件
                    generate_button.click(
                        fn=self.llmclient.generate_sql,
                        inputs=user_requirement_input,
                        outputs=sql_output
                    )
                    
                    query_button.click(
                        fn=self.database.execute_sql,
                        inputs=sql_output,
                        outputs=sql_result_output
                    )
                    
                    another_button.click(
                        fn=self.llmclient.process_exec_result,
                        inputs=sql_result_output,
                        outputs=conclusion_output
                    )
            
            # 页脚信息
            gr.HTML("""
            <div class="mt-8 text-center text-gray-500 text-sm">
                <p>© 2025 智慧农业数据分析平台 | 版本 1.0.0</p>
                <p class="mt-1">提供番茄疾病识别和农业数据智能分析服务</p>
            </div>
            """)
            
        return demo
                
    def launch(self):
        app = self.build()
        app.launch()    


if __name__ == "__main__":
    tomodel: tm.TomotaModel = tm.TomotaModel.load_model()
    GradioApp(tomodel).launch()